package org.oschina.api.report.service;

import org.oschina.Constants;
import org.oschina.Message;
import org.oschina.ResultUtil;
import org.oschina.api.BaseService;
import org.oschina.api.index.service.IndexService;
import org.oschina.api.report.dao.ReportDAO;
import org.oschina.api.report.model.Report;
import org.oschina.api.report.vo.ReportVo;
import org.oschina.api.user.user.model.User;
import org.oschina.api.user.user.service.UserService;
import org.oschina.bean.Result;
import org.oschina.handler.validator.annotation.Validate;
import org.oschina.handler.validator.annotation.ValidateField;
import org.oschina.handler.validator.filter.TextOnlyFilter;
import org.oschina.security.annotation.Require;
import org.oschina.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ReportService extends BaseService {

	@Autowired
	private ReportDAO reportDAO;
	@Autowired
	private IndexService indexService;
	@Autowired
	private UserService userService;
	
	/**
	 * 根据主键和类型返回
	 * @param major
	 * @param type
	 * @return
	 */
	public ReportVo findVoByMajorAndType(int major,int type)
	{
		return reportDAO.findVoByMajorAndType(major, type);
	}
	
	/**
	 * 根据主键和类型删除
	 * @param major
	 * @param type
	 * @return
	 */
	public Result deleteByMajorAndType(int major,int type)
	{
		if(reportDAO.deleteByMajorAndType(major, type)==0)
			return ResultUtil.getFailure(Message.ERROR_DATA_ERROR);
		
		return ResultUtil.getSuccess(Message.UPDATE_SUCCESS);
	}
	
	/**
	 * 创建
	 * @param user
	 * @param major
	 * @param type
	 * @return
	 */
	@Validate
	@Require
	public Result create
	(
		int major,int type,
		@Validate(validateField=@ValidateField(filter={TextOnlyFilter.class})) String content
	)
	{
		User user=userService.getAuthenticationInfo(getToken());
		Report report=new Report();
		report.setUser(user.getId());
		report.setMajor(major);
		report.setType(type);
		report.setContent(content);
		create(report);
		return ResultUtil.getSuccess(report);
	}
	
	
	/**
	 * 创建
	 * @param report
	 * @return
	 */
	private Report create(Report report)
	{
		report.setId(getIndex());
		report.setCreate_time(DateUtil.now());
		return reportDAO.create(report);
	}
	
	private int getIndex()
	{
		return indexService.getMajorById(Constants.INDEX_REPORT);
	}
}